package com.gzist.wlda;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.FileUtils;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.*;

public class MainActivity extends AppCompatActivity implements View.OnClickListener , View.OnLongClickListener {

    // 请求存储权限的请求码
    private static final int REQUEST_CODE_PERMISSION = 1001;
    private MediaPlayer mediaPlayer; // 声明一个 MediaPlayer 对象s

    private TextView xtPrivateLaugh;
    private TextView xtGiveWood;
    private TextView xtGhostCall;
    private TextView xtIWontLive;
    private TextView xtKuyuXi;
    private TextView xtOmg;
    private TextView xtThatOne;
    private TextView xtLittleWhiteHorse;
    private TextView xtWcnm;
    private TextView aiBanBan;
    private TextView aiPriLau;
    private TextView aiWoc;
    private TextView aiHe;
    private TextView aiSenSei;
    private TextView aiWcnm;
    private TextView linkTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        onClickListener();
        // 定义要显示的文本
        String text = (String) linkTextView.getText();
        SpannableString spannableString = new SpannableString(text);

        // 创建 ClickableSpan
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // 打开浏览器并跳转到指定的网页
                Uri uri = Uri.parse("https://blog.csdn.net/m0_74958221?type=blog");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(android.text.TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.black)); // 设置链接颜色
                ds.setUnderlineText(true); // 添加下划线
            }
        };

        // 应用 ClickableSpan 到特定的部分
        spannableString.setSpan(clickableSpan, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 设置 TextView 的文本
        linkTextView.setText(spannableString);

        // 启用链接点击
        linkTextView.setMovementMethod(LinkMovementMethod.getInstance());

        // 请求存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 初始化视图并绑定点击事件处理器
     */
    public void initView() {
        xtPrivateLaugh = findViewById(R.id.xt_private_laugh);
        xtGiveWood = findViewById(R.id.xt_give_wood);
        xtGhostCall = findViewById(R.id.xt_ghost_call);
        xtIWontLive = findViewById(R.id.xt_i_wont_live);
        xtKuyuXi = findViewById(R.id.xt_kuyu_xi);
        xtOmg = findViewById(R.id.xt_omg);
        xtThatOne = findViewById(R.id.xt_that_one);
        xtLittleWhiteHorse = findViewById(R.id.xt_little_white_horse);
        xtWcnm = findViewById(R.id.xt_wcnm);
        aiBanBan = findViewById(R.id.ai_banban);
        aiPriLau = findViewById(R.id.ai_pri_lau);
        aiWoc = findViewById(R.id.ai_woc);
        aiHe = findViewById(R.id.ai_he);
        aiSenSei = findViewById(R.id.ai_sensei);
        aiWcnm = findViewById(R.id.ai_wcnm);
        linkTextView = findViewById(R.id.linkTextView);

        // 统一设置按钮点击事件处理器
        xtPrivateLaugh.setOnClickListener(this);
        xtGiveWood.setOnClickListener(this);
        xtGhostCall.setOnClickListener(this);
        xtIWontLive.setOnClickListener(this);
        xtKuyuXi.setOnClickListener(this);
        xtOmg.setOnClickListener(this);
        xtThatOne.setOnClickListener(this);
        xtLittleWhiteHorse.setOnClickListener(this);
        xtWcnm.setOnClickListener(this);
        aiBanBan.setOnClickListener(this);
        aiPriLau.setOnClickListener(this);
        aiWoc.setOnClickListener(this);
        aiHe.setOnClickListener(this);
        aiSenSei.setOnClickListener(this);
        aiWcnm.setOnClickListener(this);
        linkTextView.setOnClickListener(this);  // 链接文本
    }

    /**
     * 为长按事件设置监听器
     */
    public void onClickListener() {
        xtPrivateLaugh.setOnLongClickListener(this);
        xtGiveWood.setOnLongClickListener(this);
        xtGhostCall.setOnLongClickListener(this);
        xtIWontLive.setOnLongClickListener(this);
        xtKuyuXi.setOnLongClickListener(this);
        xtOmg.setOnLongClickListener(this);
        xtThatOne.setOnLongClickListener(this);
        xtLittleWhiteHorse.setOnLongClickListener(this);
        xtWcnm.setOnLongClickListener(this);
        aiBanBan.setOnLongClickListener(this);
        aiPriLau.setOnLongClickListener(this);
        aiWoc.setOnLongClickListener(this);
        aiHe.setOnLongClickListener(this);
        aiSenSei.setOnLongClickListener(this);
        aiWcnm.setOnLongClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.xt_private_laugh: // 假设按钮的实际 id 是 小桃私人笑
                // 播放音频文件
                playSound(R.raw.wxtsrxs);
                // 在此处添加私密笑按钮的响应逻辑
                break;
            case R.id.xt_give_wood: // 假设按钮的实际 id 是 小桃game
                // 在此处添加给木按钮的响应逻辑
                playSound(R.raw.game);
                break;
            case R.id.xt_ghost_call: // 假设按钮的实际 id 是 xt_ghost_call
                // 在此处添加鬼叫按钮的响应逻辑
                playSound(R.raw.ku);
                break;
            case R.id.xt_i_wont_live: // 假设按钮的实际 id 是 xt_i_wont_live
                // 在此处添加我不活了按钮的响应逻辑
                playSound(R.raw.wbhl);
                break;
            case R.id.xt_kuyu_xi: // 假设按钮的实际 id 是 xt_kuyu_xi
                // 在此处添加苦呀西按钮的响应逻辑
                playSound(R.raw.kuyashi);
                break;
            case R.id.xt_omg: // 注意这里应该是 xt_omg 而不是 btn_omgs
                // 在此处添加omg按钮的响应逻辑
                playSound(R.raw.omg);
                break;
            case R.id.xt_that_one: // 假设按钮的实际 id 是 xt_that_one
                // 在此处添加那个按钮的响应逻辑
                playSound(R.raw.ng);
                break;
            case R.id.xt_little_white_horse: // 假设按钮的实际 id 是 xt_little_white_horse
                // 在此处添加小白马按钮的响应逻辑
                playSound(R.raw.bm);
                break;
            case R.id.xt_wcnm: // 假设按钮的实际 id 是 xt_little_white_horse
                // 在此处添加小白马按钮的响应逻辑
                playSound(R.raw.wcnmd);
                break;
            case R.id.ai_pri_lau: // 假设按钮的实际 id 是 ai_pri_lau
                playSound(R.raw.alssrxs);
                break;
            case R.id.ai_banban: // 假设按钮的实际 id 是 ai_banban
                // 在此处添加邦邦咔邦按钮的响应逻辑
                playSound(R.raw.bbkb);
                break;
            case R.id.ai_woc: // 假设按钮的实际 id 是 ai_woc
                // 在此处添加 woc 按钮的响应逻辑
                playSound(R.raw.wc);
                break;
            case R.id.ai_he: // 假设按钮的实际 id 是 ai_woc
                // 在此处添加 woc 按钮的响应逻辑
                playSound(R.raw.he);
                break;
            case R.id.ai_sensei: // 假设按钮的实际 id 是 ai_sensei
                // 在此处添加 sensei 按钮的响应逻辑
                // 播放音频文件
                playSound(R.raw.ss);
                break;
            case R.id.ai_wcnm: // 假设按钮的实际 id 是 ai_wcnm
                // 播放音频文件
                playSound(R.raw.alswcnm);
                break;
            default:
                // 处理未知按钮或默认情况
                break;
        }

    }

    @Override
    public boolean onLongClick(View v) {
        File destination;
        switch (v.getId()) {
            case R.id.xt_private_laugh: // 假设按钮的实际 id 是 小桃私人笑
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.wxtsrxs)+".mp3");
                copyRawResourceToFile(R.raw.wxtsrxs,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_give_wood: // 假设按钮的实际 id 是 小桃game
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.game)+".mp3");
                copyRawResourceToFile(R.raw.game,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_ghost_call: // 假设按钮的实际 id 是 xt_ghost_call
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.ku)+".mp3");
                copyRawResourceToFile(R.raw.ku,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_i_wont_live: // 假设按钮的实际 id 是 xt_i_wont_live
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.wbhl)+".mp3");
                copyRawResourceToFile(R.raw.wbhl,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_kuyu_xi: // 假设按钮的实际 id 是 xt_kuyu_xi
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.kuyashi)+".mp3");
                copyRawResourceToFile(R.raw.kuyashi,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_omg: // 注意这里应该是 xt_omg 而不是 btn_omgs
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.omg)+".mp3");
                copyRawResourceToFile(R.raw.omg,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_that_one: // 假设按钮的实际 id 是 xt_that_one
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.ng)+".mp3");
                copyRawResourceToFile(R.raw.ng,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_little_white_horse: // 假设按钮的实际 id 是 xt_little_white_horse
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.bm)+".mp3");
                copyRawResourceToFile(R.raw.bm,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.xt_wcnm: // 假设按钮的实际 id 是 xt_little_white_horse
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.wcnmd)+".mp3");
                copyRawResourceToFile(R.raw.wcnmd,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ai_pri_lau: // 假设按钮的实际 id 是 ai_pri_lau
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.alssrxs)+".mp3");
                copyRawResourceToFile(R.raw.alssrxs,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ai_banban: // 假设按钮的实际 id 是 ai_banban
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.bbkb)+".mp3");
                copyRawResourceToFile(R.raw.bbkb,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ai_woc: // 假设按钮的实际 id 是 ai_woc
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.wc)+".mp3");
                copyRawResourceToFile(R.raw.wc,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ai_he: // 假设按钮的实际 id 是 ai_woc
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.he)+".mp3");
                copyRawResourceToFile(R.raw.he,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ai_sensei: // 假设按钮的实际 id 是 ai_sensei
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.ss)+".mp3");
                copyRawResourceToFile(R.raw.ss,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ai_wcnm: // 假设按钮的实际 id 是 ai_wcnm
                destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getResources().getResourceEntryName(R.raw.alswcnm)+".mp3");
                copyRawResourceToFile(R.raw.alswcnm,destination);
                Toast.makeText(this, "已下载到"+destination.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                break;
            default:
                // 处理未知按钮或默认情况
                break;
        }

        return true;
    }

    /**
     * 播放音频文件
     *
     * @param url 音频文件的资源ID
     */
    private void playSound(int url) {
        if (mediaPlayer != null) {
            Log.d("AudioPlayer", "Releasing existing MediaPlayer.");
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }

        if (url == 0) {
            Log.w("AudioPlayer", "Invalid URL provided.");
            return;
        }

        try {
            mediaPlayer = MediaPlayer.create(this, url);
            mediaPlayer.start();
            Log.d("AudioPlayer", "MediaPlayer created and started successfully.");
        } catch (Exception e) {
            Log.e("AudioPlayer", "Error creating or starting MediaPlayer: " + e.getMessage());
        }
    }

    /**
     * 将资源文件复制到临时文件
     */
    public void copyRawResourceToFile(int resourceId, File destination) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = getResources().openRawResource(resourceId);
            out = new FileOutputStream(destination);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Toast.makeText(this, "下载完成！"+getResources().getResourceEntryName(resourceId)+".mp3", Toast.LENGTH_SHORT).show();
    }

    /**
     * 请求权限的结果回调方法
     *
     * @param requestCode 请求码，用于标识请求权限的类型
     * @param permissions 请求的权限数组
     * @param grantResults 每个权限的授予结果数组，与permissions对应
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，此处可以继续执行需要该权限的操作
            } else {
                // 权限被拒绝，提示用户授予必要的权限
                Toast.makeText(this, "请授予存储权限以下载文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

}
